<?php

namespace app\admin\controller\xmwms;

use app\admin\model\xmwms\InventoryHistory;
use app\admin\model\xmwms\OutboundOrderDetail;
use app\admin\model\xmwms\Shipment;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;
use Exception;

class OutboundOrder extends Backend
{
    /**
     * @var \app\admin\model\xmwms\OutboundOrder
     */
    protected object $model;

    protected object $productModel;

    protected object $warehouseModel;

    protected object $inventoryHistoryModel;

    protected object $outboundOrderDetailModel;

    protected object $shipmentModel;

    protected array $withJoinTable = ['wmsCustomer'];

    protected string|array $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model                    = new \app\admin\model\xmwms\OutboundOrder;
        $this->productModel             = new \app\admin\model\xmwms\Product();
        $this->warehouseModel           = new \app\admin\model\xmwms\Warehouse();
        $this->inventoryHistoryModel    = new InventoryHistory;
        $this->outboundOrderDetailModel = new OutboundOrderDetail();
        $this->shipmentModel            = new Shipment();
    }

    /**
     * 查看
     */
    public function index(): void
    {
        $this->request->filter(['strip_tags', 'trim']);
        // 如果是select则转发到select方法,若select未重写,其实还是继续执行index
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->with(['outboundOrderDetail' => function ($query) {
                $query->field('id,order_product_no,outbound_no,product_id,actual_quantity,price,total_price,warehouse_shelf_id,remark')->with(['product' => function ($queryProduct) {
                    $queryProduct->field('id,product_no,bar_code,name,brand_id,unit_id,spec')->with(['wmsUnit' => function ($queryUnit) {
                        $queryUnit->field('id,name');
                    }
                    ]);
                }
                ]);
            }, 'admin'                    => function ($queryAdmin) {
                $queryAdmin->field('id,username');
            }])
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['wmsCustomer' => ['id', 'name', 'address', 'city']]);
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $product_detail = $data['product_detail'];
            if (empty($product_detail)) {
                $this->error('请添加产品物料明细');
            }
            $outbound_no = date('Ymd-His') . '-' . rand(10000000, 99999999);
            for ($i = 0; $i < count($product_detail); $i++) {
                $product_id = $product_detail[$i]['product_id'];
                if ($product_id <= 0) $this->error('请选择产品物料');
                $plan_quantity   = $product_detail[$i]['plan_quantity'];
                $actual_quantity = $product_detail[$i]['actual_quantity'];
                if ($plan_quantity <= 0 || $actual_quantity <= 0) $this->error('请填写合适的产品数量');

                $p = $this->productModel->where('id', $product_id)->field('total_stock_num,name')->find();
                if ($actual_quantity > $p['total_stock_num']) {
                    $this->error('库存剩余' . $p['total_stock_num'] . '--' . $p['name']);
                }
                $warehouse_type = $this->warehouseModel->where('id', $product_detail[$i]['warehouse_shelf_id'])->value('warehouse_type');
                if ($warehouse_type !== 'warehouse_shelf') {
                    $this->error('第' . ($i + 1) . '个产品，货架选择有误!');
                }
            }

            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }

                for ($j = 0; $j < count($product_detail); $j++) {
                    $price           = $product_detail[$j]['price'];
                    $actual_quantity = $product_detail[$j]['actual_quantity'];
                    OutboundOrderDetail::create([
                        'outbound_no'        => $outbound_no,
                        'order_product_no'   => $product_detail[$j]['order_product_no'],
                        'product_id'         => $product_detail[$j]['product_id'],
                        'warehouse_shelf_id' => $product_detail[$j]['warehouse_shelf_id'],
                        'plan_quantity'      => $product_detail[$j]['plan_quantity'],
                        'actual_quantity'    => $actual_quantity,
                        'price'              => $price,
                        'total_price'        => $actual_quantity > 0 && $price > 0 ? round($actual_quantity * $price, 2) : 0,
                        'remark'             => $product_detail[$j]['remark'],
                    ]);
                }

                $data['admin_id']       = $this->auth->id;
                $data['outbound_no']    = $outbound_no;
                $data['product_detail'] = json_encode($product_detail);
                $result                 = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 编辑
     */
    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        $outbound_no = $row['outbound_no'];
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);

            $product_detail = $data['product_detail'];
            if (empty($product_detail)) {
                $this->error('请添加产品物料明细');
            }

            for ($i = 0; $i < count($product_detail); $i++) {
                $product_id = $product_detail[$i]['product_id'];
                if ($product_id <= 0) $this->error('请选择产品物料');
                $plan_quantity   = $product_detail[$i]['plan_quantity'];
                $actual_quantity = $product_detail[$i]['actual_quantity'];
                if ($plan_quantity <= 0 || $actual_quantity <= 0) $this->error('请填写合适的产品数量');

                $p = $this->productModel->where('id', $product_id)->field('total_stock_num,name')->find();
                if ($actual_quantity > $p['total_stock_num']) {
                    $this->error('库存剩余' . $p['total_stock_num'] . '--' . $p['name']);
                }
                $warehouse_type = $this->warehouseModel->where('id', $product_detail[$i]['warehouse_shelf_id'])->value('warehouse_type');
                if ($warehouse_type !== 'warehouse_shelf') {
                    $this->error('第' . ($i + 1) . '个产品，货架选择有误!');
                }
            }

            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }

                for ($j = 0; $j < count($product_detail); $j++) {
                    $price            = $product_detail[$j]['price'];
                    $actual_quantity  = $product_detail[$j]['actual_quantity'];
                    $product_id       = $product_detail[$j]['product_id'];
                    $order_product_no = $product_detail[$j]['order_product_no'];
                    $res              = $this->outboundOrderDetailModel->where('order_product_no', $order_product_no)->find();
                    if ($res) {
                        $this->outboundOrderDetailModel->where('order_product_no', $order_product_no)->update([
                            'outbound_no'        => $outbound_no,
                            'product_id'         => $product_id,
                            'warehouse_shelf_id' => $product_detail[$j]['warehouse_shelf_id'],
                            'plan_quantity'      => $product_detail[$j]['plan_quantity'],
                            'actual_quantity'    => $actual_quantity,
                            'price'              => $price,
                            'total_price'        => $actual_quantity > 0 && $price > 0 ? round($actual_quantity * $price, 2) : 0,
                            'remark'             => $product_detail[$j]['remark'],
                        ]);
                    } else {
                        $this->outboundOrderDetailModel->create([
                            'outbound_no'        => date('Ymd-His') . '-' . rand(10000000, 99999999),
                            'order_product_no'   => $product_detail[$j]['order_product_no'],
                            'product_id'         => $product_detail[$j]['product_id'],
                            'warehouse_shelf_id' => $product_detail[$j]['warehouse_shelf_id'],
                            'plan_quantity'      => $product_detail[$j]['plan_quantity'],
                            'actual_quantity'    => $actual_quantity,
                            'price'              => $price,
                            'total_price'        => $actual_quantity > 0 && $price > 0 ? round($actual_quantity * $price, 2) : 0,
                            'remark'             => $product_detail[$j]['remark'],
                        ]);
                    }

                    $orderProductNo[] = $order_product_no;
                }
                if (!empty($orderProductNo)) {
                    $this->outboundOrderDetailModel->where('outbound_no', $outbound_no)->whereNotIn('order_product_no', $orderProductNo)->delete();
                }

                $data['admin_id']       = $this->auth->id;
                $data['audit_status']   = 0;
                $data['product_detail'] = json_encode($product_detail);
                $result                 = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
        $row['product_detail'] = json_decode($row['product_detail'], true);
        $this->success('', [
            'row' => $row
        ]);
    }

    public function audit(): void
    {
        $id  = $this->request->param('id');
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($row['audit_status'] == 1) {
            $this->error('已审核');
        }

        $outbound_no = $row['outbound_no'];
        $type        = $row['type'];
        $detail      = $this->outboundOrderDetailModel->where('outbound_no', $outbound_no)->select();

        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {

                foreach ($detail as $k => $v) {
                    $product_id      = $v['product_id'];
                    $actual_quantity = $v['actual_quantity'];
                    $this->productModel->where('id', $product_id)->dec('total_stock_num', $actual_quantity)->update();

                    $form_type = $this->inventoryHistoryModel->typeToFormType($type, 'out');
                    InventoryHistory::create([
                        'order_no'           => $outbound_no,
                        'form_type'          => $form_type,
                        'product_id'         => $product_id,
                        'quantity'           => $actual_quantity,
                        'warehouse_shelf_id' => $v['warehouse_shelf_id'],
                        'admin_id'           => $this->auth->id,
                        'price'              => $v['price'],
                        'total_price'        => $v['total_price']
                    ]);
                }

                $result = $row->save(['audit_status' => 1]);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        $this->error(__('Parameter error'));
    }

    /**
     * 发货
     */
    public function shipment(): void
    {
        $outbound_order_id = $this->request->param('outbound_order_id');
        $outboundOrder     = $this->model->where('id', $outbound_order_id)->find();
        if (!$outboundOrder) {
            $this->error(__('Record not found'));
        } else {
            if ($outboundOrder['audit_status'] != 1) {
                $this->error('订单未审核，暂不能发货');
            }
        }

        $shipment          = $this->shipmentModel->where('outbound_order_id', $outbound_order_id)->find();
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($shipment[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $result = false;
            Db::startTrans();
            try {
                $data['outbound_order_id'] = $outbound_order_id;
                $data['shipment_time']     = strtotime($data['shipment_time']);
                $data['admin_id']          = $this->auth->id;
                if (empty($shipment)) {
                    $result = $this->shipmentModel->create($data);
                    $this->model->where('id', $outbound_order_id)->update(['shipment_status' => 1]);
                } else {
                    $result = $this->shipmentModel->where('outbound_order_id', $outbound_order_id)->update($data);
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        if (empty($shipment)) {
            $shipment = [
                'outbound_order_id' => $outbound_order_id,
                'courier_number'    => '',
                'carrier_id'        => 0,
                'shipment_time'     => '',
                'remark'            => ''
            ];
        }
        $this->success('', [
            'row' => $shipment
        ]);
    }

}